package org.game.ddd.editor.support;

import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.shape.Line;
import org.game.ddd.editor.model.CellModel;
import org.game.ddd.editor.model.LineModel;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractCellCreate {
    protected List<BorderPane> createBorderPaneList(List<CellModel> cellModelList) {
        List<BorderPane> borderPanes = new ArrayList<>();

        for (CellModel cellModel : cellModelList) {
            borderPanes.add(createBorderPane(cellModel));
        }

        return borderPanes;
    }

    protected BorderPane createBorderPane(CellModel cellModel) {
        BorderPane borderPane = new BorderPane();

        borderPane.setLayoutX(cellModel.getLayoutX());
        borderPane.setLayoutY(cellModel.getLayoutY());

        borderPane.setCenter(createNumbers(cellModel.getNumbers()));

        combination(borderPane, createBorderLine(cellModel.getTopLine()), 0, cellModel.getTopLine().getAlignment());
        combination(borderPane, createBorderLine(cellModel.getBottomLine()), 1, cellModel.getBottomLine().getAlignment());
        combination(borderPane, createBorderLine(cellModel.getLeftLine()), 2, cellModel.getLeftLine().getAlignment());
        combination(borderPane, createBorderLine(cellModel.getRightLine()), 3, cellModel.getRightLine().getAlignment());


        return borderPane;
    }

    protected Label createNumbers(List<Integer> list) {
        StringBuffer stringBuffer = new StringBuffer();

        for (Integer integer : list) {
            stringBuffer.append(integer + "/");
        }

        return new Label(stringBuffer.substring(0, stringBuffer.length() - 1));
    }

    protected Line createBorderLine(LineModel lineModel) {
        if (lineModel == null) {
            return null;
        }

        Line line = new Line();
        if (lineModel.getEndX() != null)
            line.setEndX(lineModel.getEndX());
        if (lineModel.getEndY() != null)
            line.setEndY(lineModel.getEndY());
        return line;
    }

    protected void combination(BorderPane borderPane, Line line, int direction, String alignment) {
        if (line == null || borderPane == null) {
            return;
        }

        if (direction == 0) {
            borderPane.setTop(line);
        } else if (direction == 1) {
            borderPane.setBottom(line);
        } else if (direction == 2) {
            borderPane.setLeft(line);
        } else if (direction == 3) {
            borderPane.setRight(line);
        }

        if (alignment.equals("CENTER")) {
            borderPane.setAlignment(line, Pos.CENTER);
        } else if (alignment.equals("BOTTOM_RIGHT")) {
            borderPane.setAlignment(line, Pos.BOTTOM_RIGHT);
        }
    }
}